/*
 * Project: BoboDesignPattern
 * 
 * File Created at 2020年5月16日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package test.lesson9.leetcode;

/**
 * @Type T20200516_JZOF_18
 * @Desc
 * @author 52489
 * @date 2020年5月16日
 * @Version V1.0
 */
public class T20200516_JZOF_18 {

    public static ListNode deleteNode(ListNode head, int val) {
        ListNode tmp = head;
        if (head.val == val) {
            head = head.next;
            return head;
        }
        while (null != head) {
            if (null != head.next && head.next.val == val) {
                ListNode curr = head.next;
                if (null != curr.next) {

                    head.next = curr.next;
                } else {
                    head.next = null;
                }
                return tmp;
            }

            head = head.next;
        }
        return tmp;
    }

    // 比较简的写法
    public static ListNode deleteNode1(ListNode head, int val) {
        if (head.val == val) {
            return head.next;
        }
        ListNode curr = head;
        while (null != curr.next) {
            if (curr.next.val == val) {
                curr.next = curr.next.next;
                break;
            } else {
                curr = curr.next;
            }
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(4);
        node.next = new ListNode(5);
        node.next.next = new ListNode(1);
        node.next.next.next = new ListNode(9);
        ListNode head = deleteNode(node, 5);
        while (null != head) {
            System.out.println(head.val);
            head = head.next;
        }
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}